package com.penton.util.widget;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Timer;

import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Environment;
import android.os.StatFs;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

/**
 * 相机控件
 * 
 * @author pengjianbo 
 * $Id$
 */
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
	
	private Context mContext;
	
	private SurfaceHolder mHolder;

	private Camera mCamera;

	private Button mPaiBtn, mRtPaiBtn, mSaveBtn;
	
	private Button mFlalgtBtn;

	private AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback();

	private byte[] mImageArray;
	
	private boolean mFlashNoOff = true;
	
	private int mContiNum = 1;
	
	private Timer mTimer;
	
	private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera";
	
	private boolean mPaiFlag = true;

	public CameraView(Context context) {
		super(context);
	}

	public CameraView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.mContext = context;
		mTimer = new Timer();
		mHolder = this.getHolder();
		mHolder.addCallback(this);
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		
	}

	public CameraView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		try {
			/* 打开相机 */
			mCamera = Camera.open();
			
			mCamera.setPreviewDisplay(holder);
		} catch (IOException exception) {
			mCamera.release();
			mCamera = null;
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		initCamera();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		stopCamera();
		mCamera.release();
		mCamera = null;
	}
	
	/**
	 * 设置相机按钮监听器
	 * @param pai 拍照
	 * @param rtPai 重拍
	 * @param save 保存
	 * @param flash 闪光灯
	 */
	public void setClickListener(Button pai, Button rtPai, Button save, Button flash) {
		this.mPaiBtn = pai;
		this.mRtPaiBtn = rtPai;
		this.mSaveBtn = save;
		this.mFlalgtBtn = flash;
		
		mPaiBtn.setOnClickListener(new PaiBtnClickListener());
		mRtPaiBtn.setOnClickListener(new RestartPaiClickListener());
		mSaveBtn.setOnClickListener(new SaveBtnClickListener());File f = new File(path);
		mFlalgtBtn.setOnClickListener(new FlashBtnClickListener());
	}
	
	/**
	 * 初始化相机
	 */
	private void initCamera() {
		if (mCamera != null) {
			try {
				Camera.Parameters parameters = mCamera.getParameters();
				parameters.setPictureFormat(PixelFormat.JPEG);
				parameters.setPictureSize(1024, 768);

				mCamera.setParameters(parameters);
				mCamera.startPreview();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 停止拍照
	 */
	private void stopCamera() {
		if (mCamera != null) {
			try {
				/* 停止预览 */
				mCamera.stopPreview();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 拍照按钮事件
	 */
	public class PaiBtnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			mCamera.autoFocus(mAutoFocusCallback);
			//mContiThread.start();
		}
	}

	/**
	 * 重拍按钮事件
	 */
	public final class RestartPaiClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			mPaiBtn.setVisibility(View.VISIBLE);
			/* 重新设定Camera */
			stopCamera();
			initCamera();
		}
	}
	
	/**
	 * 设置连拍次数
	 * @param count
	 */
	public void setContiPai(int count) {
		this.mContiNum = count;
	}

	/**
	 * 保存图片按钮
	 */
	public final class SaveBtnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			saveFunction();
		}
	}
	
	private void saveFunction() {
        
		if (mImageArray.length > 0) {
			if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
				Toast.makeText(mContext, "SD卡不存在", Toast.LENGTH_LONG).show();
				return;
			} else {
				
				String storage = Environment.getExternalStorageDirectory().toString();
	            StatFs fs = new StatFs(storage);
	            long available = fs.getAvailableBlocks() * fs.getBlockSize();
	            if ( available < mImageArray.length ) {
	            		//空间不足	
	            		Toast.makeText(mContext, "空间不足", Toast.LENGTH_LONG).show();
	            		return ;
	            }
	            
				try {
					/* 文件不存在就创建 */
					File f = new File(path);

					if (!f.exists()) {
						f.mkdir();
					}
					
					File file = new File(f.getPath() + "/yes.jpg");
					if(!file.exists()) {
                        //创建文件
                        file.createNewFile();
					}
					
					FileOutputStream fos = new FileOutputStream(file);
                    fos.write(mImageArray);
                    fos.close();
                    Toast.makeText(mContext, mImageArray.length + "保存到" + file.getPath(), Toast.LENGTH_LONG).show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		} else {
			Toast.makeText(mContext, "没有获取到图片", Toast.LENGTH_LONG).show();
		}
		
		mPaiFlag = false;
	
	}

	/**
	 * 闪光灯控制
	 */
	private final class FlashBtnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			mFlashNoOff = !mFlashNoOff;
			Camera.Parameters parameters = mCamera.getParameters(); 
			if ( mFlashNoOff ) {
				/*闪光灯*/
				parameters.setFlashMode(Camera.Parameters.FLASH_MODE_ON);//FLASH_MODE_TORCH：手电筒
			} else {
				parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
			}
			
			mCamera.setParameters(parameters);
		}
	};
	
	public final class AutoFocusCallback implements
			android.hardware.Camera.AutoFocusCallback {
		public void onAutoFocus(boolean focused, Camera camera) {
			/* 对到焦点拍照 */
			if (focused) {
				if (mCamera != null) {
					//拍摄照片
					mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
				}
			}
		};

		/**
		 * 快门按下的时候onShutter()被回调
		 */
		private ShutterCallback shutterCallback = new ShutterCallback() {
			public void onShutter() {
				/*发出提示用户的声音*/
				ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_MUSIC, ToneGenerator.MAX_VOLUME);
				tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
			}
		};

		private PictureCallback rawCallback = new PictureCallback() {
			public void onPictureTaken(byte[] data, Camera camera) {
				/* 要处理raw data?写?否 */
			}
		};

		private PictureCallback jpegCallback = new PictureCallback() {
			public void onPictureTaken(byte[] data, Camera camera) {
				/* 取得相片 */
				try {
					
					mImageArray = data;

					mPaiBtn.setVisibility(View.GONE);
					mSaveBtn.setVisibility(View.VISIBLE);
					mRtPaiBtn.setVisibility(View.VISIBLE);

					Toast.makeText(mContext, "拍照成功", Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
	}
	
	private Thread mContiThread = new Thread() {
		@Override
		public void run() {
			mCamera.autoFocus(mAutoFocusCallback);
			for ( int i = 0; i < mContiNum; i++ ) {
					
				try {
					if ( !mPaiFlag ) {
						mPaiFlag = true;
						stopCamera();
						initCamera();
						saveFunction();
					}
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	};

}
